<template>
  <!-- 父组件的行记录显示 -->
  <ContentWrap class="mb-4">
    <el-card>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div class="info-item">
          <span class="info-label">聚集名称：</span>
          <span class="info-value">{{ gatherData?.gatherName || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">聚集人数：</span>
          <span class="info-value">{{ gatherData?.warnPersonCount || 0 }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">开始时间：</span>
          <span class="info-value">{{
              gatherData?.startTime ? dateTimeFormatter(gatherData.startTime) : '-'
            }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">结束时间：</span>
          <span class="info-value">{{
              gatherData?.endTime ? dateTimeFormatter(gatherData.endTime) : '-'
            }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">预警时间：</span>
          <span class="info-value">{{
              gatherData?.createTime ? dateTimeFormatter(gatherData.createTime) : '-'
            }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">聚集地址：</span>
          <span class="info-value">{{ gatherData?.gatherAddress || '-' }}</span>
        </div>
      </div>
    </el-card>
  </ContentWrap>

  <!-- 视图切换按钮 -->
  <ContentWrap class="mb-4">
    <div class="view-mode-switch">
      <el-button
        @click="toggleViewMode('table')"
        :type="viewMode === 'table' ? 'primary' : 'default'"
        icon="el-icon-table"
      >
        表格模式
      </el-button>
      <el-button
        @click="toggleViewMode('map')"
        :type="viewMode === 'map' ? 'primary' : 'default'"
        icon="el-icon-map-location"
      >
        地图模式
      </el-button>

      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap v-if="viewMode === 'table'">
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      ref="gatherPersonTable"
    >
      <el-table-column label="参与人员" align="center" prop="personName">
        <template #default="scope">
          <el-tooltip :content="scope.row.idNumber || '无证件号'" placement="top">
            <el-button link type="primary" @click="openDetail(scope.row.personId)">
              {{ scope.row.personName }}
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="聚集时间"
        align="center"
        prop="locationTime"
        width="180px"
      />
      <el-table-column
        label="预警时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="定位地址"
        align="center"
        prop="address"
        min-width="200px"
      />
      <el-table-column
        label="状态"
        align="center"
        prop="isRead"
        width="160px"
      >
        <template #header>
          <div style="display: flex; align-items: center; justify-content: center;">
            <span>状态</span>
            <el-button
              type="text"
              size="small"
              style="margin-left: 30px; color: #409EFF;"
              @click="handleMarkAllRead"
              :disabled="!list.length"
            >
              全选
            </el-button>
          </div>
        </template>
        <template #default="scope">
          <div style="display: inline-flex; align-items: center;">
            <template v-if="scope.row.isRead === 0">
              <el-icon color="#F56C6C" size="18">
                <Message/>
              </el-icon>
              <span style="margin-left: 6px; color: #F56C6C;">未读</span>
            </template>

            <template v-else-if="scope.row.isRead === 1">
              <el-icon color="#67C23A" size="18">
                <Check/>
              </el-icon>
              <span style="margin-left: 6px; color: #67C23A;">已读</span>
            </template>

            <el-button
              v-if="scope.row.isRead === 0"
              type="text"
              size="small"
              style="margin-left: 12px; color: #409EFF;"
              @click="handleMarkSingleRead(scope.row)"
            >
              阅读
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 地图模式 -->
  <ContentWrap v-if="viewMode === 'map'" class="map-content-wrap">
    <div class="map-container">
      <!-- 添加点击事件阻止默认行为 -->
      <div id="personMap" ref="mapRef" class="map" @click.prevent></div>

      <!-- 地图信息弹窗 -->
      <el-dialog
        v-model="showMarkerDetail"
        v-if="showMarkerDetail || selectedPerson"
        title="人员详情"
        width="400px"
        :close-on-click-modal="false"
        append-to-body
        :before-close="handleDialogClose"
        :modal="true"
        :destroy-on-close="false"
        class="marker-dialog"
      >
        <div v-if="selectedPerson" class="marker-detail">
          <div class="detail-item">
            <span class="detail-label">参与人员：</span>
            <span class="detail-value">{{ selectedPerson.personName || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">预警时间：</span>
            <span class="detail-value">{{
                selectedPerson.createTime ? dateTimeFormatter(selectedPerson.createTime) : '-'
              }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">经度：</span>
            <span class="detail-value">{{ selectedPerson.lng || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">纬度：</span>
            <span class="detail-value">{{ selectedPerson.lat || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">定位地址：</span>
            <span class="detail-value">{{ selectedPerson.address || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">定位时间：</span>
            <span class="detail-value">{{ selectedPerson.locationTime || '-' }}</span>
          </div>
        </div>
      </el-dialog>
    </div>
  </ContentWrap>

</template>

<script setup lang="ts">
import { onMounted, ref, reactive, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from 'vue-i18n'
import Pagination from '@/components/Pagination/index.vue'
import { dateFormatter, dateTimeFormatter } from '@/utils/formatTime'
import L from 'leaflet'
import 'leaflet.label'
import 'leaflet/dist/leaflet.css'
import { Message, Check } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

import {
  FormattedWarningGatherPersonRespVO,
  WarningGatherPersonApi,
} from '@/api/member/warninggatherperson'
import { WarningGatherVO } from '@/api/member/warninggather'
import router from "@/router";

/** 聚集预警参与人员关联表组件 */
defineOptions({ name: 'WarningGatherPerson' })

const message = useMessage()
const { t } = useI18n()
const route = useRoute()

// 视图模式：table-表格模式，map-地图模式
const viewMode = ref<'table' | 'map'>('table')
// 地图实例
let mapInstance: L.Map | null = null
// 标记点图层组
let markerLayer: L.FeatureGroup<any> | null = null
// 地图容器引用
const mapRef = ref<HTMLDivElement | null>(null)
// 是否显示标记详情
const showMarkerDetail = ref(false)
// 当前选中的人员
const selectedPerson = ref<FormattedWarningGatherPersonRespVO | null>(null)
// 中心标记点
const centerMarker = ref<L.Marker<any> | null>(null)

// 父组件传递的聚集主表数据
const gatherData = ref<WarningGatherVO | null>(null)
const loading = ref(true)
const list = ref<FormattedWarningGatherPersonRespVO[]>([])
const total = ref(0)
// 表格ref（用于获取数据）
const gatherPersonTable = ref(null)

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  gatherId: route.params.id as string,
  personId: undefined,
})

// 读取 .env 中的环境变量（关键！）
const tileUrl = import.meta.env.VITE_MAP_TILE_URL; // 瓦片地址
const errorTileUrl = import.meta.env.VITE_MAP_ERROR_TILE_URL; // 错误图地址
const attribution = import.meta.env.VITE_MAP_ATTRIBUTION; // 版权信息
// 路由相关
const openDetail = (personId: number) => {
  if (!personId) {
    console.error('人员ID不存在')
    return
  }

  router.push({
    name: 'PersonDetail',
    params: { id: personId.toString() }
  })
}

// 弹窗关闭时重置状态
const handleDialogClose = () => {
  showMarkerDetail.value = false
  selectedPerson.value = null
}

/** 切换视图模式 */
const toggleViewMode = (mode: 'table' | 'map') => {
  viewMode.value = mode
  if (mode === 'map') {
    nextTick(() => {
      initMap()
    })
  }
}

// 单条标记为已读
const handleMarkSingleRead = async (row) => {
  try {
    await WarningGatherPersonApi.markSingleRead(row.id)
    row.isRead = 1
    ElMessage.success('标记已读成功')
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '网络异常'
    ElMessage.error('标记已读失败：' + errorMsg)
  }
}

// 全部标记为已读
const handleMarkAllRead = async () => {
  const unreadRows = list.value.filter(row => row.isRead === 0)
  if (!unreadRows.length) {
    ElMessage.info('已无未读记录')
    return
  }

  try {
    const unreadIds = unreadRows.map(row => row.id)
    await WarningGatherPersonApi.markBatchRead(unreadIds)
    unreadRows.forEach(row => {
      row.isRead = 1
    })
    ElMessage.success(`成功标记${unreadIds.length}条记录为已读`)
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '批量标记已读失败'
    ElMessage.error(errorMsg)
  }
}

/** 初始化地图 */
const initMap = () => {
  if (!mapRef.value) return

  // 清除现有地图实例
  if (mapInstance) {
    mapInstance.remove()
  }

  // 创建地图实例
  mapInstance = L.map(mapRef.value, {
    minZoom: 10,
    maxZoom: 16,
    attributionControl: false
  })

  // 设置离线地图瓦片源
  L.tileLayer(tileUrl, {
    errorTileUrl: errorTileUrl,
    attribution: attribution,
    tileSize: 256,
    zoomOffset: 0
  }).addTo(mapInstance);
  // L.tileLayer('/map-tiles/{z}/{x}/{y}/tile.png', {
  //   errorTileUrl: '',
  //   tileSize: 256,
  //   zoomOffset: 0
  // }).addTo(mapInstance)

  // 创建标记点图层组
  markerLayer = L.featureGroup().addTo(mapInstance)

  // 添加地图容器点击事件处理，防止页面移动
  mapRef.value.addEventListener('click', (e) => {
    e.stopPropagation()
    e.preventDefault()
  }, { passive: false })

  // 添加人员标记
  addPersonMarkers()

  // 调整地图视野
  if (list.value.length > 0) {
    const firstValidPoint = list.value.find(person => person.lng && person.lat)
    if (firstValidPoint) {
      setMapCenter(Number(firstValidPoint.lat), Number(firstValidPoint.lng), 14)
    } else {
      setMapViewToShowAllMarkers()
    }
  } else {
    mapInstance.setView([30.2741, 120.1551], 13)
  }
}

/** 设置地图中心 */
const setMapCenter = (lat: number, lng: number, zoom: number = 14) => {
  if (!mapInstance) return

  // 移除之前的中心标记
  if (centerMarker.value) {
    const markerAny = centerMarker.value as any;
    if (mapInstance.hasLayer(markerAny)) {
      mapInstance.removeLayer(markerAny);
    }
  }

  // 添加新的中心标记
  const centerIcon = L.divIcon({
    className: 'center-marker',
    html: `<div class="center-icon-inner">
             <i class="el-icon-location"></i>
           </div>`,
    iconSize: [36, 36],
    iconAnchor: [18, 36]
  });

  // 创建中心标记
  const newMarker = L.marker([lat, lng], {
    icon: centerIcon,
    zIndexOffset: 100
  });

  // 设置穿透样式
  newMarker.on('add', () => {
    setTimeout(() => {
      const markerEl = newMarker.getElement();
      if (markerEl) {
        markerEl.style.pointerEvents = 'none';
        markerEl.style.zIndex = '100';
      }
    }, 0);
  });

  centerMarker.value = newMarker;
  mapInstance.addLayer(newMarker as any);
  mapInstance.setView([lat, lng], zoom);
}

/** 添加人员标记点 */
const addPersonMarkers = () => {
  if (!markerLayer || !mapInstance) return

  // 清除现有标记
  markerLayer.clearLayers()

  // 添加新标记
  list.value.forEach(person => {
    if (person.lng && person.lat && markerLayer) {
      const customIcon = L.divIcon({
        className: 'person-marker',
        html: `<div style="width: 36px; height: 36px; background-color: #b94242; border: 2px solid white; border-radius: 50% 50% 50% 0; transform: rotate(-45deg); display: flex; align-items: center; justify-content: center; color: white; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);">
                 <i class="el-icon-user" style="transform: rotate(45deg); font-size: 18px;"></i>
               </div>`,
        iconSize: [36, 36],
        iconAnchor: [18, 36],
      })

      // 创建标记并添加到图层
      const marker = L.marker([Number(person.lat), Number(person.lng)], {
        icon: customIcon,
        zIndexOffset: 1000
      }).addTo(markerLayer as any)

      // 标记点点击事件处理
      marker.on('click', async (event: L.LeafletMouseEvent) => {
        // 阻止事件传播和默认行为
        event.originalEvent.stopPropagation();
        event.originalEvent.preventDefault();

        // 保持当前滚动位置
        window.scrollTo({ top: window.scrollY, behavior: 'auto' });

        // 设置选中人员
        selectedPerson.value = null;
        await nextTick();
        selectedPerson.value = { ...person };
        await nextTick();
        showMarkerDetail.value = true;

        // 确保弹窗显示
        setTimeout(() => {
          if (!showMarkerDetail.value) {
            showMarkerDetail.value = true;
          }
        }, 100);
      })

      // 添加弹出信息
      marker.bindTooltip(person.personName || '未知人员', {
        permanent: true,
        direction: 'top',
        className: 'person-label'
      })
    }
  })
}

/** 调整地图视野以显示所有标记 */
const setMapViewToShowAllMarkers = () => {
  if (!mapInstance || !markerLayer || list.value.length === 0) return

  const coordinates = list.value
    .filter(person => person.lng && person.lat)
    .map(person => L.latLng(Number(person.lat), Number(person.lng)))

  if (coordinates.length > 0) {
    const bounds = L.latLngBounds(coordinates)
    mapInstance.fitBounds(bounds, {
      padding: [50, 50],
      maxZoom: 15
    })
  }
}

/** 解析父组件传递的行数据 */
const parseParentRowData = () => {
  try {
    const rowDataStr = route.query.rowData as string | undefined;
    if (!rowDataStr) {
      console.warn('路由query中未找到rowData参数');
      return;
    }

    let decodedData: string;
    try {
      decodedData = decodeURIComponent(rowDataStr);
    } catch (decodeError) {
      throw new Error(`数据解码失败: ${(decodeError as Error).message}`);
    }

    gatherData.value = JSON.parse(decodedData) as WarningGatherVO;

  } catch (error) {
    console.error('解析父组件数据失败:', error);
    message.error('加载聚集信息失败');
  }
};

// 监听路由变化
watch(
  () => [route.params, route.query],
  () => {
    setTimeout(parseParentRowData, 0);
  },
  { immediate: true, deep: true }
);

// 监听弹窗显示状态
watch(showMarkerDetail, (newVal) => {
  if (newVal && mapInstance) {
    // 保持地图容器高度
    const mapContainer = document.querySelector('.map-container') as HTMLElement | null;
    if (mapContainer) {
      mapContainer.style.height = '600px';
      mapContainer.style.overflow = 'hidden';
    }

    // 防止页面滚动
    document.body.style.overflow = 'hidden';
    mapInstance.invalidateSize();
  } else {
    // 恢复页面滚动
    document.body.style.overflow = '';
  }
})

// 监听视图模式变化
watch(viewMode, (newMode) => {
  if (newMode === 'map') {
    // 保存并保持滚动位置
    const scrollPos = window.scrollY;
    nextTick(() => {
      initMap();
      window.scrollTo({ top: scrollPos, behavior: 'auto' });
    })
  }
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WarningGatherPersonApi.getWarningGatherPersonPage(queryParams)
    list.value = data.list
    total.value = data.total

    if (viewMode.value === 'map') {
      await nextTick(() => {
        addPersonMarkers()
        const firstValidPoint = list.value.find(person => person.lng && person.lat)
        if (firstValidPoint) {
          setMapCenter(Number(firstValidPoint.lat), Number(firstValidPoint.lng))
        }
      })
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    message.error(t('common.getListFailed'))
  } finally {
    loading.value = false
  }
}

// 监听列表数据变化
watch(list, (newList) => {
  if (viewMode.value === 'map' && newList.length > 0) {
    addPersonMarkers()
    const firstValidPoint = newList.find(person => person.lng && person.lat)
    if (firstValidPoint) {
      setMapCenter(Number(firstValidPoint.lat), Number(firstValidPoint.lng))
    }
  }
})

/** 初始化 */
onMounted(() => {
  setTimeout(parseParentRowData, 100);
  getList()

  window.addEventListener('resize', () => {
    if (mapInstance) {
      mapInstance.invalidateSize()
    }
  })
})

// 组件卸载时清理
onUnmounted(() => {
  if (mapInstance) {
    mapInstance.remove()
    mapInstance = null
  }
  window.removeEventListener('resize', () => {
    if (mapInstance) {
      mapInstance.invalidateSize()
    }
  })
})
</script>

<style scoped>
.info-item {
  padding: 1px 0;
}

.info-label {
  display: inline-block;
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.info-value {
  color: #303133;
  word-break: break-all;
}

:deep(.el-card) {
  border-radius: 4px;
}

.view-mode-switch {
  display: flex;
  gap: 10px;
}

.map {
  width: 100%;
  height: 100%;
}

.map-pagination {
  margin-top: 15px;
  text-align: right;
}

.marker-detail {
  padding: 10px 0;
}

.detail-item {
  margin-bottom: 12px;
}

.detail-label {
  display: inline-block;
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.detail-value {
  color: #303133;
  word-break: break-all;
}

/* 地图容器样式 */
.map-content-wrap {
  position: relative;
  min-height: 600px;
  flex-shrink: 0;
}

.map-container {
  position: relative;
  height: 600px !important;
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 600px;
  max-height: 600px;
  transition: none !important;
}

/* 弹窗样式 */
:deep(.marker-dialog) {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  z-index: 10000 !important;
}

:deep(.el-dialog__wrapper) {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 !important;
  overflow: hidden !important;
  position: fixed !important;
}

/* 地图相关样式穿透 */
:deep(.leaflet-popup-content-wrapper) {
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.person-marker),
:deep(.center-marker),
:deep(.custom-marker) {
  display: block !important;
  visibility: visible !important;
  z-index: 1000 !important;
}

:deep(.leaflet-marker-icon) {
  display: block !important;
  opacity: 1 !important;
}

:deep(.mt-15px) {
  margin-top: 0 !important;
}

:deep(.mb-15px) {
  margin-bottom: 0 !important;
}

:deep(.el-pagination) {
  margin-left: 340px;
}

:deep(.person-label) {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid #ccc;
  border-radius: 3px;
  padding: 4px 6px;
  margin-left: 15px;
  margin-top: -25px;
  font-size: 12px;
  white-space: nowrap;
}

:deep(.center-marker) {
  display: block !important;
  visibility: visible !important;
  pointer-events: none !important;
}

:deep(.center-marker .center-icon-inner) {
  width: 36px;
  height: 36px;
  background-color: #2c3e50;
  border: 2px solid white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  pointer-events: none !important;
}

:deep(.center-marker .el-icon-location) {
  font-size: 20px;
}

:deep(.leaflet-container) {
  height: 100% !important;
  width: 100% !important;
  overflow: hidden !important;
  position: relative !important;
  z-index: 1;
}

/* 禁用全局平滑滚动 */
:root {
  scroll-behavior: auto !important;
}
</style>
